package utils

import (
	"log"

	"gitee.com/shiwjlinux/shoplink/config"
	"github.com/streadway/amqp"
)

func ConnectToRabbitMQ() (*amqp.Connection, *amqp.Channel, error) {
	conn, err := amqp.Dial(config.RabbitMQURL)
	if err != nil {
		log.Fatalf("Failed to connect to RabbitMQ: %v", err)
		return nil, nil, err
	}

	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open a channel: %v", err)
		return nil, nil, err
	}

	return conn, ch, nil
}

// DeclareQueue函数用于声明一个队列
func DeclareQueue(ch *amqp.Channel, queueName string) (amqp.Queue, error) {
	// 声明一个队列，参数分别为队列名称、是否持久化、是否自动删除、是否排他、是否等待、其他参数
	q, err := ch.QueueDeclare(queueName, true, false, false, false, nil)
	// 如果声明队列失败，则打印错误信息并返回空队列和错误
	if err != nil {
		log.Fatalf("Failed to declare a queue: %v", err)
		return amqp.Queue{}, err
	}
	// 返回队列和nil
	return q, nil
}

func PublishMessage(ch *amqp.Channel, queueName string, body []byte) error {
	err := ch.Publish("", queueName, false, false, amqp.Publishing{
		ContentType:  "application/json",
		Body:         body,
		DeliveryMode: amqp.Persistent,
	})
	if err != nil {
		log.Fatalf("Failed to publish a message: %v", err)
		return err
	}
	return nil
}
